import 'package:http/http.dart';
import 'dart:convert';
import 'package:intl/intl.dart';

class WorldTime{
  String? location;
  String? time;
  String? flag; // 国旗icon
  String? url;
  bool isDaytime = true;  //是否白天
  // 构造方法
  WorldTime({this.location,this.flag,this.url});
  Future <void> getData() async{
    try {
      // http request
    var Url = "http://worldtimeapi.org/api/timezone/$url";
    // Response 类型 
    Response response = await get(Uri.parse(Url));
    // response.body 才是请求回来的data
    // 解析json 转 map
    Map data = jsonDecode(response.body);
    //print(data);
    //print(data['title']);
    String datetime = data['datetime'];
    String offset = data['utc_offset'].substring(1,3);


    // 创建时间对象
    // 格式化时间 并加上时差
    DateTime now = DateTime.parse(datetime);
    now = now.add(Duration(hours: int.parse(offset)));
    print(now);
    //time = now.toString();  // 2022-05-15 09:40:52.134566Z
    isDaytime = now.hour > 6 && now.hour<18 ? true :false;
    time = DateFormat.jm().format(now);  // 会提示上午还是下午

    }catch(e){
      print(e);
      time = "could not get time";
    }
    
   

  }
}